package com.jsnkj.basic.activity

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.TypedValue
import android.view.MenuItem
import android.view.MotionEvent
import android.view.View
import androidx.annotation.RequiresApi
import androidx.fragment.app.Fragment
import com.jsnkj.basic.LibraryConfig
import com.jsnkj.basic.R
import com.jsnkj.basic.advertisement.AdvertisementManager
import com.jsnkj.basic.config.RewardsConfig
import com.jsnkj.basic.config.SpConfig
import com.jsnkj.basic.databinding.ActivityMainBinding
import com.jsnkj.basic.dialog.OpenMainRedDialog
import com.jsnkj.basic.fragment.HomeFragment
import com.jsnkj.basic.fragment.InviteFriendsFragment
import com.jsnkj.basic.fragment.MineFragment
import com.jsnkj.basic.fragment.RedPacketFragment
import com.jsnkj.basic.fragment.RedPacketViewModel
import com.jsnkj.basic.fragment.VideoFragment
import com.jsnkj.basic.mvvm.BaseKtActivity
import com.jsnkj.basic.util.DoubleClickHelper1
import com.jsnkj.basic.util.ErrorResultUtil
import com.jsnkj.basic.util.RewardsUtil
import com.jsnkj.basic.util.SharePreferencesUtil
import com.google.android.material.bottomnavigation.BottomNavigationMenuView
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.hzhj.openads.domain.HJAdError
import com.hzhj.openads.listener.HJOnAdsSdkBannerListener
import com.hzhj.openads.listener.HJOnAdsSdkRewardListener
import com.jeremyliao.liveeventbus.LiveEventBus
import java.lang.reflect.Field
import java.util.Timer
import java.util.TimerTask


class MainActivity : BaseKtActivity<ActivityMainBinding, RedPacketViewModel>(),
    BottomNavigationView.OnNavigationItemSelectedListener {

    override val layoutId: Int
        get() = R.layout.activity_main


    private var fragments: ArrayList<Fragment>? = null

    private var mainHandler = Handler(Looper.getMainLooper())
    private var bannerRunnable: Runnable? = null

    //打开红包弹窗
    var openDialog: OpenMainRedDialog? = null


    override fun initView(savedInstanceState: Bundle?) {
        if (LibraryConfig.isHiddenHomeFragment()) {
            mVDB.bvHomeNavigation.menu.findItem(R.id.menu_home).setVisible(false)
        }
        // 不使用图标默认变色
        mVDB.bvHomeNavigation.itemIconTintList = null
        mVDB.bvHomeNavigation.setOnNavigationItemSelectedListener(this)
        adjustNavigationIcoSize(mVDB.bvHomeNavigation)

        if (fragments == null) {
            fragments = ArrayList()
        } else {
            fragments?.clear()
        }

        fragments!!.add(HomeFragment.newInstance())
        fragments!!.add(RedPacketFragment.newInstance())
        fragments!!.add(VideoFragment.newInstance())
        fragments!!.add(InviteFriendsFragment.newInstance())
        fragments!!.add(MineFragment.newInstance())

        mVDB.vpHomePager.setAdapter(
            com.jsnkj.basic.adapter.MyFragmentPagerAdapter(
                supportFragmentManager,
                fragments
            )
        )
        mVDB.vpHomePager.setOffscreenPageLimit(fragments!!.size)

        mVDB.bvHomeNavigation.selectedItemId = R.id.menu_read_packet

        postBannerAd()
        initBannerAd()

        //重置开屏时间, 减SpConfig.OPEN_MAIN_AD_TIME 跳转首页就弹出插屏
        val currentTime = System.currentTimeMillis() / 1000 - SpConfig.OPEN_MAIN_AD_TIME - 1
        SharePreferencesUtil.getInstance().putLong(SpConfig.MAIN_OPEN_AD_TIME, currentTime)
        SharePreferencesUtil.getInstance().putBoolean(SpConfig.APP_LOCK_SCREEN, true)

        //弹出插屏广告
        AdvertisementManager.showLoadInteraction(this@MainActivity)

        LiveEventBus.get<String>("openfd").observe(this) {
            com.jsnkj.basic.util.LogUtils.e("打开福袋")
            showDialog()
            mVM.postAdreWards()
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            showMainRedView(mVDB.floatingButton)
        }
    }

    override fun bindEvent() {
        super.bindEvent()

        mVM.postAdreWardsResult.observe(this) {
            dismissDialog()
            RewardsConfig.goldMoney = it.coins
            SharePreferencesUtil.getInstance().clearAdBeanList()

            if (null == openDialog) {
                openDialog = OpenMainRedDialog(
                    this@MainActivity,
                    object : OpenMainRedDialog.onItemClickListener {
                        override fun openItemClickListener() {
                            showLoadRewardVideo(0)
                        }

                        override fun closeCallBack() {

                            //弹出插屏广告
                            AdvertisementManager.showLoadInteraction(
                                this@MainActivity,
                                SpConfig.AD_TIME
                            )

                            val currentTime = System.currentTimeMillis() / 1000
                            SharePreferencesUtil.getInstance()
                                .putLong(SpConfig.MAIN_OPEN_AD_TIME, currentTime)
                        }

                        override fun increaseRewardCallBack() {
                            showLoadRewardVideo(1)
                        }
                    })
            }
            openDialog?.showDialog()
        }

        mVM.postAdWardsReceiveResult.observe(this) {
            dismissDialog()
            showResultDialog(RewardsConfig.goldMoney.toString())
            startShowMainRedView()
        }

        mVM.errorResult.observe(this) {
            dismissDialog()
            ErrorResultUtil.errorResultToast(this@MainActivity, it)
        }
    }


    override fun onNavigationItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {

            R.id.menu_home -> {
                mVDB.vpHomePager.setCurrentItem(0)
                return true
            }

            R.id.menu_read_packet -> {
                mVDB.vpHomePager.setCurrentItem(1)
                return true
            }

            R.id.menu_video -> {
                mVDB.vpHomePager.setCurrentItem(2)
                return true
            }

            R.id.menu_invite -> {
                mVDB.vpHomePager.setCurrentItem(3)
                return true
            }

            R.id.menu_mine -> {
                mVDB.vpHomePager.setCurrentItem(4)
                return true
            }

            else -> {}
        }
        return false
    }


    @SuppressLint("RestrictedApi")
    private fun adjustNavigationIcoSize(navigation: BottomNavigationView) {
        val menuView = navigation.getChildAt(0) as BottomNavigationMenuView
        for (i in 0 until menuView.childCount) {
            val iconView = menuView.getChildAt(i).findViewById<View>(android.R.id.icon)
            val layoutParams = iconView.layoutParams
            val displayMetrics = getResources()!!.displayMetrics
            layoutParams.height =
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40f, displayMetrics).toInt()
            layoutParams.width =
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40f, displayMetrics).toInt()
            iconView.layoutParams = layoutParams
        }
    }

    override fun onBackPressed() {
        if (com.jsnkj.basic.util.DoubleClickHelper.isOnDoubleClick()) {
            // 移动到上一个任务栈，避免侧滑引起的不良反应
            moveTaskToBack(false)
            //            finishApp(); // app 返回桌面后再次点击app图标启动 不要重新载入启动页面
            Handler().postDelayed({
                // 进行内存优化，销毁掉所有的界面
                com.jsnkj.basic.util.ActivityStackManager.getInstance().finishAllActivities()
            }, 300)
        } else {
            com.jsnkj.basic.util.ToastUtils.show(R.string.home_exit_hint)
        }
    }


    /**
     * 每隔 3-5秒请求一次Banner广告
     */
    private fun postBannerAd() {
        // 初始化 Runnable 对象
        bannerRunnable = object : Runnable {
            override fun run() {
                com.jsnkj.basic.util.LogUtils.e("MainActivity 每隔几秒请求一次Banner广告 ")
                if (!AdvertisementManager.getAdShowLoad(RewardsConfig.adBanner)) {
                    return
                }
                if (SpConfig.isError) {
                    mainHandler.removeCallbacks(bannerRunnable!!);
                    return
                }

                if (loadBannerAd) {
                    initBannerAd()
                }

                //定时弹出插屏广告
                AdvertisementManager.showLoadInteraction(this@MainActivity)
                // 再次调用 postDelayed 来循环执行，而不是直接调用 run，
                // 因为 run 并不会再次将任务加入消息队列
                mainHandler.postDelayed(this, SpConfig.BANNER_TIME) // 5000 毫秒后再次执行
            }
        }

    }


    var loadBannerAd = true

    fun initBannerAd() {
        AdvertisementManager.loadHjBannerAds(this@MainActivity,object:HJOnAdsSdkBannerListener{
            override fun onAdLoadSuccess(p0: String?) {
                AdvertisementManager.showHJBannerAds( mVDB.flBanner)
            }

            override fun onAdLoadError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("启动banner广告 加载失败：$p1"+","+p0?.msg)
            }

            override fun onAdShown() {

            }

            override fun onAdClicked() {
                RewardsUtil.addGoldNumber(AdvertisementManager.getAdSettingListBean(RewardsConfig.adBanner)!!.reward_num as Int, RewardsConfig.adBanner)
            }

            override fun onAdClosed() {

            }

            override fun onAdAutoRefreshed() {

            }

            override fun onAdAutoRefreshFail(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("启动banner广告 自动刷新失败：$p1"+p0!!.msg)
            }

        })
//        AdvertisementManager.loadBanner(
//            this@MainActivity,
//            SharePreferencesUtil.getInstance().getInt("app_screenWidth", 350) - 40,
//            mVDB.flBanner,
//            object : com.tb.mob.TbManager.BannerLoadListener {
//                override fun onFail(s: String) {
//                    BurialPointUtil.bannerAdEvent("fail")
//
//                    LogUtils.e("启动banner广告 加载失败：$s")
//                    mVDB.flBanner.visibility = View.GONE
//                    loadBannerAd = false
//                }
//
//                override fun onDismiss() {
//                    mVDB.flBanner.visibility = View.GONE
//                }
//
//                override fun onClicked() {}
//
//                override fun onExposure(position: com.tb.mob.bean.Position) {
//                    BurialPointUtil.bannerAdEvent("show")
//
//                    loadBannerAd = true
//                    mVDB.flBanner.visibility = View.VISIBLE
//                    RewardsUtil.addGoldNumber(position.ecpm, RewardsConfig.adBanner)
//                    // 创建新的布局参数对象，并设置新的宽度和高度
//                    val layoutParams = LinearLayout.LayoutParams(
//                        mVDB.flBanner.measuredWidth, mVDB.flBanner.measuredHeight
//                    )
//                    mVDB.flBanner.layoutParams = layoutParams
//                }
//            })
    }


    override fun onResume() {
        super.onResume()
        com.jsnkj.basic.util.LogUtils.e("MainActivity  onResume()")
        mainHandler.removeCallbacks(bannerRunnable!!)
        // 开始定时器
        mainHandler.postDelayed(bannerRunnable!!, SpConfig.BANNER_TIME)
    }


    override fun onPause() {
        super.onPause()
        com.jsnkj.basic.util.LogUtils.e("MainActivity  onPause()")
        // 取消定时器，避免内存泄漏
        mainHandler.removeCallbacks(bannerRunnable!!)
    }

    override fun onDestroy() {
        super.onDestroy()

        mainHandler.removeCallbacksAndMessages(null);
        mVDB.bvHomeNavigation.setOnNavigationItemSelectedListener(null)
    }

    private var progressNumber = 0
    private var redTimer: Timer? = null

    //var positionBean: Position? = null


    var isMainReceiveReward = false

    fun showLoadRewardVideo(type: Int) {
        SharePreferencesUtil.getInstance()
            .putBoolean(SpConfig.APP_LOCK_SCREEN, false)

        isMainReceiveReward = false

        AdvertisementManager.loadHjRewardAds(this@MainActivity,object:HJOnAdsSdkRewardListener{
            override fun onVideoAdLoadSuccess(p0: String?) {
                //加载成功
                var option : HashMap<String,String> = hashMapOf(
                    "name" to "激励视频",
                    "position" to "mainActivity"
                )
                AdvertisementManager.showHJRewardAds(option);
            }

            override fun onVideoAdPlayEnd() {

            }

            override fun onVideoAdPlayStart() {

            }

            override fun onVideoAdClicked() {

            }

            override fun onVideoRewarded(p0: String?) {
               com.jsnkj.basic.util.LogUtils.e("激励视频奖励回调MainActivity,onVideoRewarded="+p0)
            }

            override fun onVideoAdClosed() {
                    com.jsnkj.basic.burialpoint.BurialPointUtil.playJlspAdEvent("show")
                    com.jsnkj.basic.util.LogUtils.e("激励视频  onClose()")
                    if (!isMainReceiveReward) {
                        if (1 == type) {
                            startShowMainRedView()
                        } else {
                            mVM.postAdreWardsReceive()
                        }
                    }
                    SharePreferencesUtil.getInstance().putBoolean(SpConfig.APP_LOCK_SCREEN, true)
                    RewardsUtil.addGoldNumber(AdvertisementManager.getAdSettingListBean(RewardsConfig.adStimulate)!!.reward_num as Int, RewardsConfig.adStimulate)
            }

            override fun onVideoAdLoadError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("激励视频加载失败回调onVideoAdLoadError="+p1)
            }

            override fun onVideoAdPlayError(p0: HJAdError?, p1: String?) {
                com.jsnkj.basic.util.LogUtils.e("激励视频播放失败回调onVideoAdLoadError="+p1)
            }

        })

    }

    fun startShowMainRedView() {
        progressNumber = 0
        mVDB.progressView.progress = progressNumber
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            showMainRedView(mVDB.floatingButton)
        }

        LiveEventBus.get<String>("readFragmentRefresh").post("1");
    }


    fun startRedTimer(){
        if (null != redTimer) {
            redTimer!!.cancel()
        }
        redTimer = Timer()
        redTimer?.schedule(object : TimerTask() {
            override fun run() {
                Handler(Looper.getMainLooper()).post {
                    com.jsnkj.basic.util.LogUtils.e("当前进度： progressview.progress = ${mVDB.progressView.progress}")
                    if (mVDB.progressView.progress == 100) {
                        mVDB.imgClickPrize.visibility = View.VISIBLE
                        redTimer?.cancel()
                    } else {
                        mVDB.imgClickPrize.visibility = View.INVISIBLE
                    }
                    progressNumber = progressNumber + 1
                    if (progressNumber > 100) {
                        progressNumber = 100
                        redTimer!!.cancel()
                    }

                    //需要执行的任务
                    mVDB.progressView.progress = progressNumber
                }
            }
        }, 0, 500)
    }
    @RequiresApi(Build.VERSION_CODES.HONEYCOMB)
    fun showMainRedView(view: View) {
        try {
            view.visibility = View.VISIBLE

            var paramsX = SharePreferencesUtil.getInstance().getInt("main_activity_kf_params_x", 0)
            var paramsY = SharePreferencesUtil.getInstance().getInt("main_activity_kf_params_y", 0)
            if (0 == paramsX) {
                paramsX = 10
                view.x = paramsX.toFloat()
                SharePreferencesUtil.getInstance().putInt("main_activity_kf_params_x", paramsX)
            }

            if (0 == paramsY) {
                paramsY = 600
                SharePreferencesUtil.getInstance().putInt("main_activity_kf_params_y", paramsY)
            }

            com.jsnkj.basic.util.LogUtils.e("当前进度：paramsX = $paramsX   paramsY = $paramsY")

            view.x = paramsX.toFloat()
            view.y = paramsY.toFloat()
            //加载红包
            startRedTimer();
            if (mVDB.progressView.progress == 100) {
                mVDB.imgClickPrize.visibility = View.VISIBLE
            } else {
                mVDB.imgClickPrize.visibility = View.INVISIBLE
            }

            // 设置悬浮按钮的触摸事件监听
            view.setOnTouchListener(object : View.OnTouchListener {
                private var offsetX = 0f
                private var offsetY = 0f
                private var initialTouchX = 0f
                private var initialTouchY = 0f

                private var rawX = 0f
                private var rawY = 0f

                override fun onTouch(v: View, event: MotionEvent): Boolean {
                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            rawX = event.rawX
                            rawY = event.rawY

                            offsetX = event.rawX - view.x
                            offsetY = event.rawY - view.y
                            return true
                        }

                        MotionEvent.ACTION_MOVE -> {
                            initialTouchX = event.rawX - offsetX
                            initialTouchY = event.rawY - offsetY
                            view.x = initialTouchX
                            view.y = initialTouchY
                            return true
                        }

                        MotionEvent.ACTION_UP -> {
                            var main_activity_kf_params_x = SharePreferencesUtil.getInstance()
                                .getInt("main_activity_kf_params_x", 0)
                            var main_activity_kf_params_y = SharePreferencesUtil.getInstance()
                                .getInt("main_activity_kf_params_y", 0)

                            //检测移动的距离，如果很微小可以认为是点击事件
                            if (Math.abs(main_activity_kf_params_x - initialTouchX) < 10 && Math.abs(
                                    main_activity_kf_params_y - initialTouchY
                                ) < 10
                            ) {
                                try {
                                    var field: Field =
                                        View::class.java.getDeclaredField("mListenerInfo")
                                    field.setAccessible(true)
                                    var fileGet: Any = field.get(v)
                                    field = fileGet.javaClass.getDeclaredField("mOnClickListener")
                                    field.setAccessible(true)
                                    fileGet = field.get(fileGet)
                                    if (fileGet != null && fileGet is View.OnClickListener) {
                                        fileGet.onClick(v)
                                    }
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }

                            SharePreferencesUtil.getInstance()
                                .putInt("main_activity_kf_params_x", initialTouchX.toInt())
                            SharePreferencesUtil.getInstance()
                                .putInt("main_activity_kf_params_y", initialTouchY.toInt())

                            return true
                        }
                    }
                    return false
                }
            })

            DoubleClickHelper1.click(view) {
                if (mVDB.progressView.progress == 100) {
                    showDialog()
                    mVM.postAdreWards()
                    startShowMainRedView()
                    showMainRedView(view)
                } else {
                    com.jsnkj.basic.util.ToastUtils.show("奖励准备中")
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

